package com.ziytek.web.citizen.configuration;

/**
 * @author fenghx
 * @version 1.0
 * @className UpdateBatchById
 * Description:
 * @date 2024/3/25 17:15
 */

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import java.io.Serial;
import java.io.Serializable;

/**
 * 通过ID批量更新
 *
 * @author fengh
 */
@RefreshScope
public class UpdateBatchById extends AbstractMethod implements Serializable {
    @Serial
    private static final long serialVersionUID = 4198102405483580486L;

    /**
     * @param methodName 方法名
     * @since 3.5.0
     */
    protected UpdateBatchById(String methodName) {
        super(methodName);
    }

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        var sqlMethod = MySqlMethod.UPDATE_BATCH_BY_ID;
        var sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), this.sqlSet(tableInfo), tableInfo.getKeyColumn(), this.sqlIn(tableInfo.getKeyProperty()));
        var sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
    }

    private String sqlSet(TableInfo tableInfo) {
        var fieldList = tableInfo.getFieldList();
        var sb = new StringBuilder();

        for (var fieldInfo : fieldList) {
            sb.append("<if test=\"ew.updateFields.contains(&quot;").append(fieldInfo.getColumn()).append("&quot;)\">")
                    .append(fieldInfo.getColumn()).append(" =\n")
                    .append("CASE ").append(tableInfo.getKeyColumn()).append("\n")
                    .append("<foreach collection=\"list\" item=\"et\" >\n")
                    .append("WHEN #{et.").append(tableInfo.getKeyProperty()).append("} THEN #{et.").append(fieldInfo.getProperty()).append("}\n")
                    .append("</foreach>\n").append("END ,\n")
                    .append("</if>\n");

        }
        return "<set>\n" + sb + "</set>";
    }

    private String sqlIn(String keyProperty) {

        return "<foreach collection=\"list\" item=\"et\" separator=\",\" open=\"(\" close=\")\">\n" +
                "#{et." + keyProperty + "}" +
                "</foreach>\n";
    }
}

